package com.tanhua.server.controller;

import com.tanhua.commons.utils.ImagesStreamUtils;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserInfoService userInfoService;


    /**
     * 保存用户信息
     *
     * @param userInfo
     * @param token
     * @return
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginRegInfo(@RequestBody UserInfo userInfo,
                                       @RequestHeader("Authorization") String token) {


        userInfo.setId(UserHolder.getUserId());
        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);

    }

    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {


        File headPhotoFile = ImagesStreamUtils.convertMultipartFiletoFile(headPhoto);
        userInfoService.updateHead(headPhotoFile, UserHolder.getUserId());

        return ResponseEntity.ok(null);
    }

    /**
     * 获取用户信息，不用传token，因为interceptor里面全局处理了
     *
     * @param userId
     * @return
     */
    @GetMapping
    public ResponseEntity<UserInfo> users(Long userId) {
        UserInfo userInfo = userInfoService.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    @PutMapping
    public ResponseEntity<Object> users(@RequestBody UserInfo userInfo) {
        Long userId = UserHolder.getUserId();
        userInfo.setId(userId);
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }

}
